const router = require('express').Router()
const {query} = require('../../db')
const { sms, mode } = require('../../config')
const Core = require('@alicloud/pop-core');
const redis = require('../../redis')

var client = new Core({
    accessKeyId: sms.accessKeyId,
    accessKeySecret: sms.accessKeySecret,
    endpoint: 'https://dysmsapi.aliyuncs.com',
    apiVersion: '2017-05-25'
  });
  
  var requestOption = {
    method: 'POST'
  };

router.post('/', async (req, res, next)=>{
    let mobile = req.body.mobile

    if(mode === 'dev') {
        res.json({
            'ok': 1,
            'data': {
                'sms_code': 1234
            }
        })
    } else {
        let code = parseInt(Math.random()*10000)
        var params = {
            "RegionId": "cn-hangzhou",
            "PhoneNumbers": mobile,
            "SignName": sms.signName,
            "TemplateCode": sms.templateId,
            "TemplateParam": `{code:${code}}`
        }

        redis.set('code_'+mobile, code, 'EX', sms.expireAt)
    
        client.request('SendSms', params, requestOption).then((result) => {
            if(result.Message === 'OK' && result.Code === 'OK') {
                res.json({
                    'ok': 1,
                    'data': {
                        'sms_code': code
                    }
                })
            } else {
                res.json({
                    'ok': 0,
                    'error': '验证码发送失败'
                })
            }
        }, (ex)=>{
            res.json({
                'ok': 0,
                'error': '发送频繁过高，请明天再试~'
            })
        })
    }

})


module.exports = router